package com.cgt.springboot.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@Aspect
@Component
public class ServiceLogAspect {
	private static final Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);

	@Before("execution(* com.cgt.springboot.service.impl.*.*(..))")
	public void before(){
		System.out.println("transaction begin");
	}

	//切面 = 通知 + 切入点
	@Around("execution(* com.cgt.springboot.service.impl.*.*(..))")
	public Object recordTimeLog(ProceedingJoinPoint joinPoint) throws Throwable {
		logger.info("===开始执行 {}.{}===",joinPoint.getTarget().getClass(),joinPoint.getSignature().getName());
		//记录开始时间 millisecond
		long begin = System.currentTimeMillis();

		//模拟一个耗时操作
//        try {
//            Thread.sleep(2000);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }

		//调用目标对象中的方法，就是service中方法
		Object result = joinPoint.proceed();

		long end = System.currentTimeMillis();

		long takeTime = end - begin;

		if (takeTime >= 3000) {
			logger.error("===========执行结束，耗时{}毫秒===============", takeTime);
		} else if (takeTime >= 2000) {
			logger.warn("===========执行结束，耗时{}毫秒===============", takeTime);
		} else {
			logger.info("===========执行结束，耗时{}毫秒===============", takeTime);
		}

		return result;
	}
}
